package com.bieber.smartpost.invoke;

import com.bieber.smartpost.httpcore.Cookie;
import com.bieber.smartpost.util.Utils;

import java.net.HttpCookie;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by bieber on 2014/11/6.
 */
public class CookieContainer {

    private static final  ConcurrentHashMap<String,Set<HttpCookie>> COOKIE_COLLECTION = new ConcurrentHashMap<String, Set<HttpCookie>>();

    private static final String COOKIE_SPLIT_TOKEN="; ";

    public static String getCookiesForCurrentInvoke(String invokeId) {
        Set<HttpCookie> cookies  = COOKIE_COLLECTION.get(invokeId);
        if(cookies==null||cookies.size()<=0){
            return "";
        }
        StringBuffer cookiesStr = new StringBuffer();
        for(HttpCookie cookie:cookies){
            String cookieValue = cookie.getValue();
            cookiesStr.append(cookie.toString()).append(COOKIE_SPLIT_TOKEN);
        }
        if(cookiesStr.length()>0){
            cookiesStr.setLength(cookiesStr.length()-COOKIE_SPLIT_TOKEN.length());
        }
        return cookiesStr.toString();
    }

    public static Collection<HttpCookie> getCookies(String invokeId){
        return COOKIE_COLLECTION.get(invokeId);
    }


    public static void cacheCookies(String invokeId,Collection<HttpCookie> cookies){
        if(cookies==null){
            return ;
        }
        Utils.COMMONS_LOGGER.debug("cache cookies for request "+invokeId+",cookies:"+cookies.toString());
        Set<HttpCookie> cachedCookies =  COOKIE_COLLECTION.get(invokeId);
        if(cachedCookies==null){
            cachedCookies = new HashSet<HttpCookie>();
            COOKIE_COLLECTION.put(invokeId,cachedCookies);
        }
        for(HttpCookie cookie:cookies){
            if(cachedCookies.contains(cookie)){
                cachedCookies.remove(cookie);
            }
            cachedCookies.add(cookie);
        }
    }

    public static void clearCookies(String invokeId){
        COOKIE_COLLECTION.remove(invokeId);
    }
}
